package com.example.prom.ok.y2022.controller.email.aws.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.*;

import java.io.DataInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.*;

@RestController
@RequestMapping("aws/email")
public class AwsEmailController {

    @PostMapping("sign")
    public void sign(@RequestHeader Map<String, String> headers, @RequestBody String msgTextString) throws Exception{
        // SignatureVersion = 1
//        String replacedText = msgTextString.replace("\\n", "\\u005c\\u006e");
//        System.out.println(replacedText);
//        Gson gson = new Gson();
//        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true) ;
//        Map<String, String> map = objectMapper.readValue(msgTextString, Map.class);
//        Map<String, String> map = gson.fromJson(replacedText, Map.class);
        Map<String, String> map = JSON.parseObject(msgTextString, Map.class);
        System.out.println(JSON.toJSONString(map));
        String signingCertURL = map.get("SigningCertURL");
        System.out.println(signingCertURL);
        String message = map.get("Message");
        System.out.println("message:"+message);
        URL url = new URL(signingCertURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        DataInputStream in = new DataInputStream(conn.getInputStream());
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate c = cf.generateCertificate(in);
        PublicKey pk = c.getPublicKey();

        StringBuilder sb = new StringBuilder();

        List<String> tmp = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            tmp.add(entry.getKey());
        }
        Collections.sort(tmp);

        for (String key : tmp) {
            if (key.equalsIgnoreCase("Signature")
                    || key.equalsIgnoreCase("SignatureVersion")
                    || key.equalsIgnoreCase("SigningCertURL")
                    || key.equalsIgnoreCase("UnsubscribeURL")
            ){
                continue;
            }
            sb.append(key);
            sb.append("\n");
            sb.append(map.get(key));
            sb.append("\n");

        }
//        String signString = replaceLast(sb.toString(), "\n", "");
//        System.out.println("signString:"+signString);
        //对Authorization字段做Base64解码。
        String signature = map.get("Signature");
        System.out.println("signature:"+signature);
        byte[] decodedSign = Base64.decodeBase64(signature);

        //认证。
        java.security.Signature signetcheck = java.security.Signature.getInstance("SHA1withRSA");
        signetcheck.initVerify(pk);
        signetcheck.update(sb.toString().getBytes());
        Boolean res = signetcheck.verify(decodedSign);
        System.out.println(res);

    }

    public static String replaceLast(String text, String regex, String replacement) {
        return text.replaceFirst("(?s)"+regex+"(?!.*?"+regex+")", replacement);
    }

    public static void main(String[] args) {
        String s = "\\"; //92
//        String s = "\n"; //10
        byte[] bytes = s.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        System.out.println(s);
    }
}
